<?php

class ShareController
{
    private $shareModel;
    private $autoUidModel;
    private $diaryListModel;
    private $followModel;

    function __construct()/*{{{*/
    {
        $this->shareModel   	=   new ShareModel();
        $this->autoUidModel 	=   new AutoUidModel();
        $this->diaryListModel   =   new DiaryListModel();
        $this->followModel      =   new FollowModel();
        $this->actions          =   array(
					'diaryShare','topicShare','userShare', 'curriculaShare', 'shorturlGetCurricula','photoShare','articleShare','anonymousShare'
				);
    }/*}}}*/
    
    public function callApi($param)/*{{{*/
    {
    	$ac = $param['action'];
    	# check $do /*{{{*/
    	$doCheck    =   $this->checkAction($ac);
    	if (!empty(AC::$errorNo))
    	{
		return  $doCheck;
    	} /*}}}*/
    
    	return $this->$ac($param);
    }/*}}}*/
    
    /**
     * 验证验证码
     * @param unknown $param
     */
    public function verifyCaptcha($param){
        $success = false;
        $info    = '';
        
    	if ($param['key'] && $param['code']) {
    	    $url        =  AC::$captchaHost.'verify?key='.$param['key'].'&code='.$param['code'];
    	    $keyjson	=  UK::getHttpResponseGET($url);
    	    $msg		=  json_decode($keyjson,true);
    	    $errnum		=  $msg['error_no'];
    	    if($errnum != 0){
    	        $info    = $msg['error_msg'];
    	    }else{
    	        $success = true;
    	        $info    = $url;
    	    }
    	}
    	
    	$result = array('success' => $success,'error_info' => $info);
    	return $result;
    }
    
    /**
     * 获取验证码
     * @param unknown $param
     * @return StdClass|multitype:string unknown
     */
    public function getCaptcha($param){
    	//获取key
    	$keyUrl 	= 	AC::$captchaHost.'getkey';
    	$keyjson	=	UK::getHttpResponseGET($keyUrl);
    	$keys		=	json_decode($keyjson,true);
    	$key		=   $keys['key'];
    	if(empty($key)){
    		return (object)array();
    	}
    	
    	$showUrl = AC::$captchaHost.'showimage?key='.$key;
    	$result = array('captcha_key'=>$key,'captcha_url'=>$showUrl);
    	if (empty(AC::CAPTCHA_SWITCH)) $result['captcha_key'] = '';
    	
    	return $result;
    }
    
    public function getDuiBaShareUrl($param) {
        $duiba_action = "pinksns://channel/biz/duiba/redirect?redirect=1&url=";
        $duiba_url = trim($param['url']);
        $duiba_share_url = trim($param['share_url']);
        
        return array('action_url' => $duiba_action.urlencode($duiba_url), 'share_url' => $duiba_share_url);
    }
    
    /**
     * 分享
     * @param unknown $param
     * @return boolean|string|unknown
     */
    public function diaryShare($param)/*{{{*/
    {
    	if (intval($param['uid']) < 1 || intval($param['bodyId']) < 1)
    	{
    		AC::$errorNo    =   'SC001';
    		return  FALSE;
    	}

    	// 查日记，取savetime
    	$diary     = new DiaryController();
    	$diaryInfo = $diary->getDiaryDetailByGuest($param);
    	if (AC::$errorNo){
    		AC::$errorNo    =   NULL;
    	}
    	
    	$action = "diary";
    	$query = array(
    			"uid"	=>	intval($param['uid']),
    			"did"	=>	intval($param['bodyId']),
    			"time"	=>	$diaryInfo['time']
    	);
    	
    	$result = $this->share_url($action, $query);
    	$url    = $result['shorurl'];
    	if (empty($url)) return '';
    	return $url;
    }/*}}}*/

    /**
     * 文章分享
     * @param unknown $param
     * @return boolean|string|unknown
     */
    public function articleShare($param)/*{{{*/
    {
        if (intval($param['author_uid']) < 1 || intval($param['aid'] < 1))
        {
            AC::$errorNo    =   'SC001';
            return  FALSE;
        }

        // 查文章
        $articleListCacheModel     = new ArticleListModel();
        $articleInfo = $articleListCacheModel->getArticleInfoByArticleBodyId($param['aid'], $param['author_uid']);
        if (AC::$errorNo){
            AC::$errorNo    =   'SC009';
            return  FALSE;
        }

        $action = "article";
        $query = array(
            "aid"	        =>	intval($param['aid']),
            "uid"	=>	intval($param['author_uid']),
            "time"	        =>	$articleInfo['time']
        );

        $result = $this->share_url($action, $query);
        $url    = $result['shorurl'];
        if (empty($url)) return '';
        return $url;
    }/*}}}*/

    /**
     * 匿名分享
     * @param unknown $param
     * @return boolean|string|unknown
     */
    public function anonymousShare($param)/*{{{*/
    {
        if (empty($param['uid']) < 1 || intval($param['bodyId'] < 1000) || intval($param['position']) < 0)
        {
            AC::$errorNo    =   'SC001';
            return  FALSE;
        }

        // 查匿名卡片详情
        $anonymousModel = new AnonymousModel();
        $anonymousInfo = [];
        if(intval($param['position']) > 0){   //评论详情
            $anonymousInfo = $anonymousModel->getCommentInfoByBodyIdPos($param['bodyId'], $param['position']);
        }else{
            $anonymousInfo = $anonymousModel->getAnonymousInfoByBodyId($param['bodyId']);
        }
        if (AC::$errorNo){
            AC::$errorNo    =   'SC009';
            return  FALSE;
        }
        if(empty($anonymousInfo)) return '';

        $action = "anonymous";
        $query = array(
            "bodyId"   =>  intval($param['bodyId']),
            "uid"   =>  intval($param['uid']),
            "position"   =>  intval($param['position']),
            "time"  =>  $anonymousInfo['create_at']
        );

        $result = $this->share_url($action, $query);
        $url    = $result['shorurl'];
        if (empty($url)) return '';
        return $url;
    }/*}}}*/

    /**
     * 分享课程表生成短链接
     * @param $param
     * @return bool|string
     * @throws Exception
     */
    public function curriculaShare($param){
    	$uid = intval($param['uid']);
    	$bodyId = intval($param['bodyId']);
    	$type = 22;//课程表类型
    	if ($uid < 1 || $bodyId < 1) {
    		AC::$errorNo    =   'SC001';
    		return  FALSE;
    	}
    	//检查课程表是否已同步
    	$cloudSyncModel = new CloudSyncContentModel();
    	$syncContent = $cloudSyncModel->getSyncDetail($uid, $bodyId, $type);
    	if (empty($syncContent)){
    		AC::$errorNo = 'SC009';//课程表不存在或者没同步
    		return FALSE;
    	}
    	$action = 'curricula';
    	$query = [
    			'uid' => $uid,
    			'bodyId' => $bodyId,
    			'type' => $type
    	];
    	$result = $this->share_url($action, $query);
    	$url = $result['shorurl'];
        return empty($url) ? '' : $url;
    }

    public function shorturlGetCurricula($param){
        $shorturl = trim($param['shortcode']);
        $type = 22;//课程表类型
        if (empty($shorturl)){
            AC::$errorNo    =   'SC001';
            return  FALSE;
        }
        if (mb_strlen($shorturl)>50){
            AC::$errorNo    =   'SC002';//短链错误
            return  FALSE;
        }

        $action = 'get_hits';
        $query = [
            'shorturl' => $shorturl
        ];
        $result = $this->share_url($action, $query);
        $longurl = $result['longurl'];
        $url_query = parse_url($longurl, PHP_URL_QUERY);
        parse_str($url_query, $out);
        if (empty($out) || !isset($out['uid']) || !isset($out['bodyId'])){
            AC::$errorNo    =   'SC002';//短链错误
            return  FALSE;
        }
        $cloudSyncModel = new CloudSyncContentModel();
        $syncContent = $cloudSyncModel->getSyncDetail($out['uid'], $out['bodyId'], $type);
        if (empty($syncContent)){
            AC::$errorNo    =   'SC009';//课程表不存在或者没同步
            return  FALSE;
        }
        if ($syncContent['type'] == 1){
            $paper = json_decode($syncContent['string1'], true);
            $syncContent['paper'] = strval($paper['paper']);
            $syncContent['string1'] = '';
        }
        $syncContent['bodyId'] = $cloudSyncModel->getBodyId($out['uid'], $syncContent['id']);
        $cloudSyncAttachModel = new CloudSyncAttachmentModel();
        $out['bodyId'] = $syncContent['bodyId'];
        $syncContent['attachment'] = $cloudSyncAttachModel->getCloudAttachment($out);
        return $syncContent;
    }
    
    private function userShare($param)/*{{{*/
    {
    	if (intval($param['uid']) < 1)
    	{
    		AC::$errorNo    =   'SC001';
    		return  FALSE;
    	}
    	
    	// 查用户，取最新表发的一篇日记时间
    	//$result		 =	$this->diaryListModel->getLastestDiary($param['uid']);
    	//$lastestTime =  $result[0]['time'];
    	 
    	$action = "user";
    	$query = array(
    			"uid"	=>	intval($param['uid']),
    			"time"	=>	'0'
    	);
    	$result = $this->share_url($action, $query);
    	$url    = $result['shorurl'];
    	if (empty($url)) return '';
    	return $url;
    }/*}}}*/
    
    public function topicShare($param)/*{{{*/
    {
    	if (intval($param['tid']) < 1){
    		AC::$errorNo    =   'SC001';
    		return  FALSE;
    	}
    	
    	// 查看话题保存时间
    	$topic  =  new GroupController();
    	$topicInfo = $topic->getTopicDetail(array('tid'=>$param['tid']));
    	if (empty($topicInfo['topic_info'])){
    		return '';
    	}

    	if (AC::$errorNo){
    		AC::$errorNo    =   NULL;
    	}

    	$action = "topic";
    	$query = array(
    			"uid"	=>	intval($topicInfo['topic_info']['uid']),
    			"tid"	=>	intval($topicInfo['topic_info']['tid']),
    			"gid"	=>	intval($topicInfo['topic_info']['gid']),
    			"time"	=>	intval($topicInfo['topic_info']['time']),
    	);
    	$result = $this->share_url($action, $query);
    	$url    = $result['shorurl'];
    	if (empty($url)) return '';
    	return $url;
    }/*}}}*/
    
    public function photoShare($param)/*{{{*/
    {
    	$res = UK::getstr(UK::cleanStr($param['res']), 80);
    	$size = UK::getstr(UK::cleanStr($param['size']), 20);
    	$source = UK::getstr(UK::cleanStr($param['source']), 20);
    	if(!in_array($source, array('planner', 'memorial'))){
    		$source = null;
    	}

    	if (AC::$errorNo){
    		AC::$errorNo    =   NULL;
    	}

    	$action = "photo";
    	$query = array(
    			"res"	=>	strval($res),
    			"size"	=>	$size,// 200,300
    			"source"	=>	$source
    	);
    	$result = $this->share_url($action, $query);
    	$url    = $result['shorurl'];
    	if (empty($url)) return '';
    	return $url;
    }/*}}}*/
    
    public function share_url($action, $query) {
    	$url = "http://share.fenfenriji.com/api.php?mod=share&do=get_url";
    	$data = array(
    			"action"=>$action,
    			"query"=>$query
    	);
    	$arr = array(
    			"time"	=>	AC::SERVER_TIME,
    			"param"	=>	json_encode($data)
    	);
    	
    	$json   = UK::getHttpResponsePOST($url, $arr);
    	$result = UK::parseData($json);
    	if ($result['errorNo'] || empty($result['data'])){
    		//TODO log
    		$logStr =   'Ti : '. AC::SERVER_TIME. "\t". date('Y/m/d H:i:s', AC::SERVER_TIME). "\taction=". $action. "param=".$arr['param'].",\t". $result['errorNo']. "\r\n";
    		UK::saveLog('error.share_url.log', $logStr, TRUE);
    		
    		AC::$errorNo    =   'SC007';
    		return '';
    	}
    	return $result['data'];
    }
    
    /**
     * 任务
     * @param unknown $param
     * @return multitype:string multitype: boolean
     */
    public function doTask ($param) {
        $uid = 0;
        if (isset($param['uid']) && $param['uid']) $uid = AC::HOST_UID;
        
        $result = array(
            'uid'        =>    strval($uid),
            'task'       =>    '',
            'gainCoin'   =>    '0',
            'type'       =>    'other',
            'conditions' =>    array(),
            'is_complete'=>    FALSE
        );
        
        if (!in_array($param['task'], AC::$taskCondition['task'])) return $result;
        if (in_array($param['type'], AC::$taskCondition['type'])) {
            $result['type'] = strval($param['type']);
        }
        
        $result['task'] = strval($param['task']);
        
        // 直接加金币
        if ($uid > 0){
            $coinTask = '';
            // 任务_分享
            if ($param['task'] == 'share'){
                $coinTask = MallApi::$task_share;
            }

            //任务_bmi测试
            if ($param['task'] == 'bmi'){
                $coinTask = MallApi::$task_bmitesting;
            }
        
            // 任务_有米视频
            if ($param['task'] == 'youmi_vedio'){
                $coinTask = MallApi::$task_system_biz_youmi_video;
            }
            
            // 任务_查看广告
            if ($param['task'] == 'ad'){
                $coinTask = MallApi::$task_system_ad;
            }
        
            // 加金币
            $api = UK::getMallApi($uid);
            $coin = $api->executeCoinTask($coinTask, 0, $result['type']);
            if ($coin && $coin['change'] > 0){
                //AC::$gainExp        =    intval($coin['exp_change']);
                AC::$gainCoin       =    intval($coin['change']);
                $result['gainCoin'] =    strval($coin['change']);
                $result['is_complete'] = TRUE;
            }
        }
        
        return  $result;
    }

    public function getShareMeList($shareInfo)/*{{{*/
    {
        if (empty($shareInfo['listMode']))/*{{{*/
        {
            $result =   $this->shareModel->getShareMeList($shareInfo);
        }
        else
        {
            if ('up' == $shareInfo['listMode'])
            {
                $result =   $this->shareModel->getShareMeListUp($shareInfo);
            }
            else
            {
                $result =   $this->shareModel->getShareMeListDown($shareInfo);
            }
        }
        if (!empty(AC::$errorNo))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
        }/*}}}*/

        if (empty($result)  ||  !is_array($result)) return  NULL;
        foreach ($result    as  &$info)
        {
            $info['detail'] =   $this->getDetailInfo($info);
        }

        return  $result;
    }/*}}}*/

    public function getMeShareList($shareInfo)/*{{{*/
    {
        if (empty($shareInfo['listMode']))/*{{{*/
        {
        $result =   $this->shareModel->getMeShareList($shareInfo);
        }
        else
        {
            if ('up' == $shareInfo['listMode'])
            {
                $result =   $this->shareModel->getMeShareListUp($shareInfo);
            }
            else
            {
                $result =   $this->shareModel->getMeShareListDown($shareInfo);
            }
        }
        if (!empty(AC::$errorNo))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
        }/*}}}*/

        if (empty($result)  ||  !is_array($result)) return  NULL;
        foreach ($result    as  &$info)
        {
            $info['detail'] =   $this->getDetailInfo($info);
        }

        return  $result;
    }/*}}}*/

    public function postShare($shareInfo)/*{{{*/
    {
        if (empty($shareInfo['uid'])  ||  empty($shareInfo['sUid']))
        {
            AC::$errorNo    =   'SC001';
            return  FALSE;
        }

        $userBaseInfo       =   $this->autoUidModel->getUserInfo($shareInfo['uid']);
        if (!isset($userBaseInfo['nickname']))
        {
            AC::$errorNo    =   'SC002';
            return  FALSE;
        }

        $sUidBaseInfo       =   $this->autoUidModel->getUserInfo($shareInfo['sUid']);
        if (!isset($sUidBaseInfo['nickname']))
        {
            AC::$errorNo    =   'SC003';
            return  FALSE;
        }

        $shareInfo['nickname']    =   $userBaseInfo['nickname'];
        $shareInfo['sNickname']   =   $sUidBaseInfo['nickname'];

        $result =   $this->shareModel->postShare($shareInfo);
        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        #  feed & statistics    /*{{{*/
        AC::$userStatistics[$shareInfo['uid']]['shareTimes']    =   1;
        AC::$userStatistics[$shareInfo['sUid']]['shareMeTimes'] =   1;
        if (isset(AC::$bodyidTypeClass[$shareInfo['type']]))
        {
            AC::$itemStatistics =   array(
                                        'shareTimes'        =>  1,
                                        'bodyidTypeClass'   =>  AC::$bodyidTypeClass[$shareInfo['type']],
                                        'uid'               =>  $shareInfo['sUid'],
                                        'bodyId'            =>  $shareInfo['bodyId'],
                                        'kitType'           =>  $shareInfo['type'],       # in Diary ,no kitType field!
                                    );
        }
        AC::$feedInfo   =   array(
                                'uid'               =>  $shareInfo['uid'],
                                'eUid'              =>  AC::$hostUserBaseInfo['uid'],
                                'eNickname'         =>  AC::$hostUserBaseInfo['nickname'],
                                'authorUid'         =>  $shareInfo['sUid'],
                                'authorNickname'    =>  $shareInfo['sNickname'],
                                'bodyId'            =>  $shareInfo['bodyId'],
                                'type'              =>  AC::FEED_SHARE,
                                'subType'           =>  $shareInfo['type'],
                                'content'           =>  $shareInfo['content'],
                            );/*}}}*/

        return  $result;
    }/*}}}*/

    public function removeShare($shareInfo)/*{{{*/
    {
        $result =   $this->shareModel->removeShare($shareInfo);
        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        #   AC::$userStatistics[$shareInfo['uid']]['shareTimes']    =   -1;
        return  $result;
    }/*}}}*/

    private function getDetailInfo($info)/*{{{*/
    {
        $type   =   $info['type'];
        $detail =   UK::getDataByBodyid($type, $info['bodyId'], ' * ');

        if (empty($detail)) $detail =   NULL;
        return  $detail;
    }/*}}}*/
	
    private function checkAccessPremission($uid)/*{{{*/
    {
        if ((AC::HOST_UID   ==  $uid))  return  TRUE;
         
        $array      =   array('uid' => AC::HOST_UID, 'fUid' => $uid, 'alarm' => TRUE);
        $isBlackMe  =   $this->followModel->isBlackMe($array);
        if (empty($isBlackMe))  return  TRUE;
         
        return  FALSE;
    }/*}}}*/
    
    private function checkAction($action)/*{{{*/
    {
    	if (in_array($action, $this->actions) && method_exists($this, $action))  return  TRUE;
    	AC::$errorNo    =   'SA004';
    	return  ' Error : call do is not exists in ShareController! ';
    }/*}}}*/
}

